﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;

namespace SLWebApp.ChildWindows
{
    public partial class ChildWindow_ShipSchedule : ChildWindow
    {
        private System.Collections.ObjectModel.ObservableCollection<ServiceReference_HB.ST_Vessels> listVess = null;//所有船信息
        ServiceReference_HB.ServiceForSLClient clientService = new ServiceReference_HB.ServiceForSLClient();//WCF服务
        System.Collections.ObjectModel.ObservableCollection<ServiceReference_HB.UM_Ports> list_port = null;//所有港口信息。

        public ServiceReference_HB.UM_VesselSchedules mUM_VesselSchedules = null;//接受传过来的船期信息。

        private string userid = string.Empty; //记录当前登陆用户的ID。

        /// <summary>为True表示是新增，
        /// 为True表示是新增，
        /// </summary>
        public bool IsAdd_Modefy = false;

        /// <summary>
        /// 增加鼠标点击事件，通知主窗体更新数据。
        /// </summary>
        public event MouseButtonEventHandler OnAddShipSchedule;//增加鼠标点击事件，通知主窗体更新数据。

        public ChildWindow_ShipSchedule(ObservableCollection<ServiceReference_HB.ST_Vessels> mListVess, string mUserId)
        {
            InitializeComponent();
            listVess = mListVess;
            userid = mUserId;//登陆用户。
            Init();
        }
        //新增时初始化一些数据。
        public void SetDefault()
        {
            if (comboxShipType.ItemsSource != null && comboxShipType.Items.Count > 5)
            {
                comboxShipType.SelectedItem = 4;
            }

        }

        public void ClearText()
        {
            progressbar.IsBusy = false;
            //清除数据
            txtVesselCNName.Text = "";
            txtVesselCNName.Tag = null;
            autoComENName_Add.Tag = null;
            txtVesselName.Text = "";
            txtTerminal.Text = "";
            txtImportVoyage.Text = "";
            txtExportVoyage.Text = "";
            datePicker_eta.Text = "";
            datePicker_etd.Text = "";
            autoboxPort1.Text = "";
            autoboxPort2.Text = "";
            comboxPort.SelectedItem = null;
            autoComENName_Add.Text = "";
            comboxSeaRoutes.SelectedItem = null;
            // comboxServiceLine.ItemsSource = null;
            txtSeaRoutes.Text = string.Empty;
            comboxVesselDate.ItemsSource = null;
           // comboxShipType.SelectedItem = null;
            rbtnState1.IsChecked = true;
            txt_eta_h.Text = "00";
            txt_eta_M.Text = "00";
            txt_etd_h.Text = "00";
            txt_etd_m.Text = "00";

            if (mListServiceLine != null)
            {
                mListServiceLine.Clear();
                mListServiceLine = null;
            }

            gridSecondRow.Height = new GridLength(30);
            gridThirdRow.Height = new GridLength(30);
            this.Height = 260;
        }

        #region //数据初始化。
        private void Init()
        {

            //if (listVess != null)
            //{
            //    this.autoComENName_Add.ItemsSource = from vess in listVess
            //                                         select vess.VSL_ENNAME + '(' + vess.VSL_CD + ')';
            //}
            if (!string.IsNullOrEmpty(userid)) //获取登陆人的名字
            {
                int intID = 0;
                int.TryParse(userid, out intID);
                clientService.GetCustomerNameAsync(intID);
                clientService.GetCustomerNameCompleted -= new EventHandler<ServiceReference_HB.GetCustomerNameCompletedEventArgs>(clientService_GetCustomerNameCompleted);
                clientService.GetCustomerNameCompleted += new EventHandler<ServiceReference_HB.GetCustomerNameCompletedEventArgs>(clientService_GetCustomerNameCompleted);

                if (intID == 1)
                    clientService.GetMainSeaRoutes_ByUserIdAsync(intID, "1");
                else
                    clientService.GetMainSeaRoutes_ByUserIdAsync(intID, "0");
                clientService.GetMainSeaRoutes_ByUserIdCompleted -= new EventHandler<ServiceReference_HB.GetMainSeaRoutes_ByUserIdCompletedEventArgs>(clientService_GetMainSeaRoutes_ByUserIdCompleted);
                clientService.GetMainSeaRoutes_ByUserIdCompleted += new EventHandler<ServiceReference_HB.GetMainSeaRoutes_ByUserIdCompletedEventArgs>(clientService_GetMainSeaRoutes_ByUserIdCompleted);

            }
            // 获取船舶类型
            clientService.GetRefCodeAsync("rv_domain ='VSL_VTYPE' or rv_domain ='抵港位置'  ", string.Empty);
            clientService.GetRefCodeCompleted -= new EventHandler<ServiceReference_HB.GetRefCodeCompletedEventArgs>(clientService_GetRefCodeCompleted);
            clientService.GetRefCodeCompleted += new EventHandler<ServiceReference_HB.GetRefCodeCompletedEventArgs>(clientService_GetRefCodeCompleted);
            //预报位置
            //clientService.GetRefCodeAsync("rv_domain ='抵港位置'", string.Empty);
            //clientService.GetRefCodeCompleted+=new EventHandler<ServiceReference_HB.GetRefCodeCompletedEventArgs>(clientService_GetRefCodeCompleted);
            //港口
            clientService.GetAllPortAsync(string.Empty, string.Empty);
            clientService.GetAllPortCompleted -= new EventHandler<ServiceReference_HB.GetAllPortCompletedEventArgs>(clientService_GetAllPortCompleted);
            clientService.GetAllPortCompleted += new EventHandler<ServiceReference_HB.GetAllPortCompletedEventArgs>(clientService_GetAllPortCompleted);
        }

        /// <summary>
        /// 让下拉框启用。
        /// </summary>
        public void SetDropdownListEnable()
        {
            //在修改进，不能启动服务航线下拉框及班期
            comboxSeaRoutes.IsEnabled = true;
            comboxServiceLine.IsEnabled = true;
            comboxVesselDate.IsEnabled = true;
        }

        void clientService_GetAllPortCompleted(object sender, ServiceReference_HB.GetAllPortCompletedEventArgs e)
        {
            list_port = e.Result;
            List<string> result = (from port in list_port
                                   select port.POT_PORTCD + '(' + port.POT_PORTLOCNNM + ')').ToList();
            this.autoboxPort1.ItemsSource = result;
            this.autoboxPort2.ItemsSource = result;
            this.dataGridPort1.ItemsSource = list_port;
            this.dataGridPort2.ItemsSource = list_port;
        }

        /// <summary>
        /// 所有总的航线
        /// </summary>
        ObservableCollection<ServiceReference_HB.MainSeaRoutes> list_allSeaRoutes = null;

        /// <summary>
        /// 航线名称完成事件。
        /// </summary>
        void clientService_GetMainSeaRoutes_ByUserIdCompleted(object sender, ServiceReference_HB.GetMainSeaRoutes_ByUserIdCompletedEventArgs e)
        {
            list_allSeaRoutes = e.Result;
            comboxSeaRoutes.ItemsSource = list_allSeaRoutes;
        }
        //配置数据完成事件
        System.Collections.ObjectModel.ObservableCollection<ServiceReference_HB.UM_Ref_Code> listRef_code = null;
        void clientService_GetRefCodeCompleted(object sender, ServiceReference_HB.GetRefCodeCompletedEventArgs e)
        {
            listRef_code = e.Result;
            //船舶类型.
            List<ServiceReference_HB.UM_Ref_Code> result_VesselType = (from refcode in listRef_code
                                                                       where refcode.RV_DOMAIN == "VSL_VTYPE"
                                                                       select refcode).ToList();
            result_VesselType.Add(new ServiceReference_HB.UM_Ref_Code { RV_LOW_VALUE = "0", RV_MEANING = "所有类型" });
            this.comboxShipType.ItemsSource = result_VesselType;
            if (result_VesselType.Count > 5)
            {
                comboxShipType.SelectedItem = result_VesselType[4];
            }
            //抵港位置
            this.comboxPort.ItemsSource = from port in listRef_code
                                          where port.RV_DOMAIN == "抵港位置"
                                          select port;
        }

        void clientService_GetCustomerNameCompleted(object sender, ServiceReference_HB.GetCustomerNameCompletedEventArgs e)
        {
            txtAgentName.Text = e.Result;
        }
        #endregion

        #region //修改数据时的初始化动作。
        public void Inited()
        {
            //清除数据
            txtVesselCNName.Text = "";
            txtVesselCNName.Tag = null;
            txtVesselName.Text = "";
            txtTerminal.Text = "";
            txtImportVoyage.Text = "";
            txtExportVoyage.Text = "";
            datePicker_eta.Text = "";
            datePicker_etd.Text = "";
            autoboxPort1.Text = "";
            autoboxPort2.Text = "";
            autoComENName_Add.Text = "";
            comboxSeaRoutes.SelectedItem = null;
            txtSeaRoutes.Text = "";
            comboxServiceLine.SelectedItem = null;
            comboxPort.SelectedItem = null;
            datePicker_eta.Text = "";
            txt_eta_h.Text = "00";
            txt_eta_M.Text = "00";
            datePicker_etd.Text = "";
            txt_etd_h.Text = "00";
            txt_etd_m.Text = "00";


            gridSecondRow.Height = new GridLength(0);
            gridThirdRow.Height = new GridLength(0);
            this.Height = 200;

            clientService.GetScheduleBy_SCD_IDAsync(mUM_VesselSchedules.SCD_ID.ToString());//先获取班期信息。
            clientService.GetScheduleBy_SCD_IDCompleted -= new EventHandler<ServiceReference_HB.GetScheduleBy_SCD_IDCompletedEventArgs>(clientService_GetScheduleBy_SCD_IDCompleted);
            clientService.GetScheduleBy_SCD_IDCompleted += new EventHandler<ServiceReference_HB.GetScheduleBy_SCD_IDCompletedEventArgs>(clientService_GetScheduleBy_SCD_IDCompleted);

            progressbar.IsBusy = true;
        }
        /// <summary>
        /// 当前船期记录.
        /// </summary>
        ServiceReference_HB.ST_Schedules mSchedules = null;
        void clientService_GetScheduleBy_SCD_IDCompleted(object sender, ServiceReference_HB.GetScheduleBy_SCD_IDCompletedEventArgs e)
        {
            mSchedules = e.Result as ServiceReference_HB.ST_Schedules;

            clientService.GetService_LinesBySLN_IDAsync(string.IsNullOrEmpty(mSchedules.SCD_SLN_ID.ToString()) ? "0" : mSchedules.SCD_SLN_ID.ToString());//再获取服务航线信息。
            clientService.GetService_LinesBySLN_IDCompleted -= new EventHandler<ServiceReference_HB.GetService_LinesBySLN_IDCompletedEventArgs>(clientService_GetService_LinesBySLN_IDCompleted);
            clientService.GetService_LinesBySLN_IDCompleted += new EventHandler<ServiceReference_HB.GetService_LinesBySLN_IDCompletedEventArgs>(clientService_GetService_LinesBySLN_IDCompleted);

        }
        //当前船期记录.完成事件。
        void clientService_GetService_LinesBySLN_IDCompleted(object sender, ServiceReference_HB.GetService_LinesBySLN_IDCompletedEventArgs e)
        {
            ServiceReference_HB.ST_SERVICE_LINES mService_Line = e.Result as ServiceReference_HB.ST_SERVICE_LINES;
            if (mService_Line != null)
            {
                //航线
                var result_SeaRout = (from table in list_allSeaRoutes
                                      where table.ID == mService_Line.SLN_SRT_ID
                                      select table).ToList();
                if (result_SeaRout != null && result_SeaRout.Count > 0)
                {
                    comboxSeaRoutes.SelectedItem = result_SeaRout[0];

                    //获取登陆人的名字
                    int intID = 0;
                    int.TryParse(userid, out intID);
                    //绑定服务航线的下拉框
                    if (intID == 1)
                        clientService.GetChildSeaRoutes_ByLineIDAsync(intID, "1", result_SeaRout[0].ID);
                    else
                        clientService.GetChildSeaRoutes_ByLineIDAsync(intID, "0", result_SeaRout[0].ID);
                }
            }

            if (mUM_VesselSchedules != null)
            {
                //英文船名
                ServiceReference_HB.ST_Vessels mVessel = GetVesselBy_VSL_CNNAME(mUM_VesselSchedules.VSL_CNNAME);
                if (mVessel != null)
                {
                    autoComENName_Add.Text = mVessel.VSL_ENNAME + '(' + mVessel.VSL_UNCODE + ')';
                    autoComENName_Add.Tag = mVessel.VSL_ID.ToString();
                    txtVesselCNName.Tag = mVessel.VSL_ENNAME;
                }
                else
                {
                    autoComENName_Add.Text = string.Empty;
                    txtVesselCNName.Tag = null;
                    autoComENName_Add.Tag = null;
                }
                //中文船名
                txtVesselCNName.Text = mUM_VesselSchedules.VSL_CNNAME;
                //船公司
                // txtVesselName.Text = mUM_VesselSchedules;

                //服务航线
                // ServiceReference_HB.MainSeaRoutes mServiceLine = GetServiceLineByName(mUM_VesselSchedules.SERVICELINE);
                //进口航次
                txtImportVoyage.Text = string.IsNullOrEmpty(mSchedules.SCD_IVOYAGE) ? "" : mSchedules.SCD_IVOYAGE;
                //出口航次
                txtExportVoyage.Text = string.IsNullOrEmpty(mSchedules.SCD_EVOYAGE) ? "" : mSchedules.SCD_EVOYAGE;
                //抵港时间
                if (mSchedules.SCD_ETA != null)
                {
                    datePicker_eta.Text = mSchedules.SCD_ETA.ToString("yyyy/MM/dd");
                    txt_eta_h.Text = mSchedules.SCD_ETA.Hour.ToString();
                    txt_eta_M.Text = mSchedules.SCD_ETA.Minute.ToString();
                }
                else
                {
                    datePicker_eta.Text = "";
                    txt_eta_h.Text = "00";
                    txt_eta_M.Text = "00";
                }
                //离港时间
                if (mSchedules.SCD_ETD != null)
                {
                    datePicker_etd.Text = mSchedules.SCD_ETD.Value.ToString("yyyy/MM/dd");
                    txt_etd_h.Text = mSchedules.SCD_ETD.Value.Hour.ToString();
                    txt_etd_m.Text = mSchedules.SCD_ETD.Value.Minute.ToString();
                }
                else
                {
                    datePicker_etd.Text = "";
                    txt_etd_h.Text = "00";
                    txt_etd_m.Text = "00";
                }

                if (!string.IsNullOrEmpty(mSchedules.SCD_CULOC))
                {
                    var result = (from port in listRef_code
                                  where port.RV_DOMAIN == "抵港位置" && port.RV_LOW_VALUE == mSchedules.SCD_CULOC
                                  select port).ToList();
                    if (result != null && result.Count > 0)
                    {
                        comboxPort.SelectedItem = result[0];
                    }
                }
                //上一港
                if (mSchedules.SCD_POT_FID != null)
                {
                    List<string> result1 = (from port in list_port
                                            where port.POT_ID == mSchedules.SCD_POT_FID.Value
                                            select port.POT_PORTCD + '(' + port.POT_PORTLOCNNM + ')').ToList();
                    if (result1 != null && result1.Count > 0)
                    {
                        autoboxPort1.Text = result1[0].ToString();
                    }
                }
                //下一港
                if (mSchedules.SCD_POT_NID != null)
                {
                    List<string> result2 = (from port in list_port
                                            where port.POT_ID == mSchedules.SCD_POT_NID.Value
                                            select port.POT_PORTCD + '(' + port.POT_PORTLOCNNM + ')').ToList();
                    if (result2 != null && result2.Count > 0)
                    {
                        autoboxPort2.Text = result2[0].ToString();
                    }
                }

                comboxServiceLine.SelectedItem = mUM_VesselSchedules.SERVICELINE;
                //引航标志
                if (mSchedules.SCD_PILOTAGE == "Y")
                {
                    rbtnYes.IsChecked = true;
                    rbtnNo.IsChecked = false;
                }
                else
                {
                    rbtnYes.IsChecked = false;
                    rbtnNo.IsChecked = true;
                }
                if (mSchedules.SCD_STATUS == "1") //状态 预报
                {
                    rbtnState1.IsChecked = true;
                    rbtnState2.IsChecked = false;

                    stackPanel_eta.Visibility = System.Windows.Visibility.Collapsed;
                    stackPanel_etd.Visibility = System.Windows.Visibility.Collapsed;
                }
                else
                {
                    rbtnState1.IsChecked = false;
                    rbtnState2.IsChecked = true;
                }
                //在修改进，不能启动服务航线下拉框及班期
                comboxSeaRoutes.IsEnabled = false;
                comboxServiceLine.IsEnabled = false;
                comboxVesselDate.IsEnabled = false;
            }
            progressbar.IsBusy = false;
        }
        #endregion

        #region 事件
        //英文船名
        private void autoComENName_Add_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (listVess == null)
                return;
            if (e.AddedItems.Count > 0)
            {
                var result = from vess in listVess
                             where vess.VSL_ENNAME + '(' + vess.VSL_UNCODE + ')' == e.AddedItems[0].ToString()
                             select vess;
                List<ServiceReference_HB.ST_Vessels> tem = result.ToList();
                if (tem.Count > 0)
                {
                    txtVesselCNName.Text = tem[0].VSL_CNNAME;
                    txtVesselCNName.Tag = tem[0].VSL_ENNAME;
                    autoComENName_Add.Tag = tem[0].VSL_ID.ToString();
                }
                else
                {
                    txtVesselCNName.Text = "";
                    txtVesselCNName.Tag = null;
                    autoComENName_Add.Tag = null;
                }
            }
        }

        //英文船名失去焦点后的事件
        private void autoComENName_Add_LostFocus(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(autoComENName_Add.Text))
            {
                txtVesselCNName.Text = "";
                txtVesselCNName.Tag = null;
            }
        }

        //选择船舶类型的事件。
        private void comboxShipType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ServiceReference_HB.UM_Ref_Code theRef_Code = this.comboxShipType.SelectedItem as ServiceReference_HB.UM_Ref_Code;
            if (theRef_Code != null)
            {
                progressbar.IsBusy = true;
                if (theRef_Code.RV_LOW_VALUE != "0")
                {
                    clientService.GetAllVesselsAsync("  vsl_vtpcode= '" + theRef_Code.RV_LOW_VALUE + "' ", string.Empty);
                }
                else if (theRef_Code.RV_LOW_VALUE == "0")
                {
                    clientService.GetAllVesselsAsync(string.Empty, string.Empty);
                }
                clientService.GetAllVesselsCompleted -= new EventHandler<ServiceReference_HB.GetAllVesselsCompletedEventArgs>(clientService_GetAllVesselsCompleted);
                clientService.GetAllVesselsCompleted += new EventHandler<ServiceReference_HB.GetAllVesselsCompletedEventArgs>(clientService_GetAllVesselsCompleted);
            }
        }

        void clientService_GetAllVesselsCompleted(object sender, ServiceReference_HB.GetAllVesselsCompletedEventArgs e)
        {
            this.autoComENName_Add.ItemsSource = from vess in e.Result
                                                 select vess.VSL_ENNAME + '(' + vess.VSL_UNCODE + ')';
            this.dataGridVesselName.ItemsSource = e.Result;
            progressbar.IsBusy = false;
        }

        //航线名称选择事件。
        private void comboxSeaRoutes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            if (e.AddedItems.Count > 0)
            {
                if (!string.IsNullOrEmpty(userid))
                {
                    //获取登陆人的名字
                    int intID = 0;
                    int.TryParse(userid, out intID);
                    ServiceReference_HB.MainSeaRoutes item = e.AddedItems[0] as ServiceReference_HB.MainSeaRoutes;
                    progressbar.IsBusy = true;
                    //绑定服务航线的下拉框
                    if (intID == 1)
                        clientService.GetChildSeaRoutes_ByLineIDAsync(intID, "1", item.ID);
                    else
                        clientService.GetChildSeaRoutes_ByLineIDAsync(intID, "0", item.ID);
                    clientService.GetChildSeaRoutes_ByLineIDCompleted -= new EventHandler<ServiceReference_HB.GetChildSeaRoutes_ByLineIDCompletedEventArgs>(clientService_GetChildSeaRoutes_ByLineIDCompleted);
                    clientService.GetChildSeaRoutes_ByLineIDCompleted += new EventHandler<ServiceReference_HB.GetChildSeaRoutes_ByLineIDCompletedEventArgs>(clientService_GetChildSeaRoutes_ByLineIDCompleted);
                    //获取班期
                }
            }
        }

        private ObservableCollection<ServiceReference_HB.MainSeaRoutes> mListServiceLine = null;
        void clientService_GetChildSeaRoutes_ByLineIDCompleted(object sender, ServiceReference_HB.GetChildSeaRoutes_ByLineIDCompletedEventArgs e)
        {
            try
            {
                mListServiceLine = e.Result;
                dataGridSchedule.ItemsSource = mListServiceLine; //comboxServiceLine.ItemsSource = mListServiceLine;
                if (mSchedules != null)
                {
                    var result = (from table in mListServiceLine
                                  where table.ID == mSchedules.SCD_SLN_ID
                                  select table).ToList();
                    if (result != null && result.Count > 0)
                    {
                        //comboxServiceLine.SelectedItem = result[0];
                    }
                }
            }
            finally
            {
                progressbar.IsBusy = false;
                txtSeaRoutes.Text = "";
                txtSeaRoutes.Tag = null;
                txtVesselName.Text = "";
                txtVesselName.Tag = null;
                comboxVesselDate.ItemsSource = null;
                // comboxVesselDate.SelectedItem = null;
                txtTerminal.Text = "";
            }
        }

        //void clientService_GetVesselNameCompleted(object sender, ServiceReference_HB.GetVesselNameCompletedEventArgs e)
        //{
        //    txtVesselName.Text = e.Result;

        //}

        //选择服务航线名称后的事件。
        private void dataGridSchedule_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                if (!string.IsNullOrEmpty(userid))
                {
                    //获取登陆人的名字
                    int intID = 0;
                    int.TryParse(userid, out intID);
                    ServiceReference_HB.MainSeaRoutes item = e.AddedItems[0] as ServiceReference_HB.MainSeaRoutes;
                    if (item == null) return;
                    txtVesselName.Text = item.CST_CSTM;
                    this.txtSeaRoutes.Text = string.IsNullOrEmpty(item.ChildRouteName) ? item.RouteName : item.ChildRouteName;
                    this.txtSeaRoutes.Tag = item.ID;
                    txtTerminal.Text = "";//先清除.
                    //班期
                    clientService.GetVesselDateAsync(intID, item.ID.ToString());
                    clientService.GetVesselDateCompleted -= new EventHandler<ServiceReference_HB.GetVesselDateCompletedEventArgs>(clientService_GetVesselDateCompleted);
                    clientService.GetVesselDateCompleted += new EventHandler<ServiceReference_HB.GetVesselDateCompletedEventArgs>(clientService_GetVesselDateCompleted);
                    ////显示预分码头.
                    //clientService.GetTermailAsync(item.ID);
                    //clientService.GetTermailCompleted -= new EventHandler<ServiceReference_HB.GetTermailCompletedEventArgs>(clientService_GetTermailCompleted);
                    //clientService.GetTermailCompleted += new EventHandler<ServiceReference_HB.GetTermailCompletedEventArgs>(clientService_GetTermailCompleted);
                    //显示船公司名称。
                    //clientService.GetVesselNameAsync(item.ID);
                    //clientService.GetVesselNameCompleted -= new EventHandler<ServiceReference_HB.GetVesselNameCompletedEventArgs>(clientService_GetVesselNameCompleted);
                    //clientService.GetVesselNameCompleted += new EventHandler<ServiceReference_HB.GetVesselNameCompletedEventArgs>(clientService_GetVesselNameCompleted);
                }
            }
        }



        //班期,选择完成事件。
        void clientService_GetVesselDateCompleted(object sender, ServiceReference_HB.GetVesselDateCompletedEventArgs e)
        {
            ObservableCollection<ServiceReference_HB.MainSeaRoutes> col = e.Result;
            if (col.Count > 0)
            {
                comboxVesselDate.ItemsSource = col;
                comboxVesselDate.SelectedItem = col[0];
            }
            else
            {
                comboxVesselDate.ItemsSource = null;
                // comboxVesselDate.SelectedItem = null;
            }
        }

        //保存按钮事件
        private void btnSave_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                progressbar.IsBusy = true;
                string state = "1";//状态。
                string terminal_id = "0";// 码头ID。
                string ucloc = "0";//预报位置。
                string P_PILOTAGE = null; //引航标志。
                string fid = "0"; //上一港口。
                string nid = "0"; //下一港口。
                string sln_id = "0"; //服务航线ID。
                string flt_id = "0";//班期ID。
                DateTime eta = DateTime.MinValue;//抵港时间
                DateTime etd = DateTime.MinValue;//离港时间
                string huar1 = string.IsNullOrEmpty(this.txt_eta_h.Text) ? "00" : this.txt_eta_h.Text;
                string huar2 = string.IsNullOrEmpty(this.txt_etd_h.Text) ? "00" : this.txt_etd_h.Text;
                string minete1 = string.IsNullOrEmpty(this.txt_eta_M.Text) ? "00" : this.txt_eta_M.Text;
                string minete2 = string.IsNullOrEmpty(this.txt_etd_m.Text) ? "00" : this.txt_etd_m.Text;

                eta = string.IsNullOrEmpty(datePicker_eta.Text) ? DateTime.MinValue : DateTime.Parse(datePicker_eta.Text + " " + huar1 + ":" + minete1);
                etd = string.IsNullOrEmpty(datePicker_etd.Text) ? eta.AddDays(1) : DateTime.Parse(datePicker_etd.Text + " " + huar2 + ":" + minete2);
                //状态
                if (rbtnState1.IsChecked.Value)
                    state = "1";
                else
                    state = "2";
                //靠泊码头。
                if (txtTerminal.Tag != null)
                    terminal_id = txtTerminal.Tag.ToString();
                // 预报位置
                ServiceReference_HB.UM_Ref_Code ref_code = comboxPort.SelectedItem as ServiceReference_HB.UM_Ref_Code;
                if (ref_code != null)
                {
                    ucloc = ref_code.RV_LOW_VALUE;
                }
                //引航标志
                if (rbtnYes.IsChecked.Value)
                    P_PILOTAGE = "Y";
                else
                    P_PILOTAGE = "N";
                //进出品港口的，上一港，下一港。
                if (list_port != null && list_port.Count > 0)
                {
                    var result1 = from port in list_port
                                  where port.POT_PORTCD + '(' + port.POT_PORTLOCNNM + ')' == autoboxPort1.Text
                                  select port;
                    var result2 = from port in list_port
                                  where port.POT_PORTCD + '(' + port.POT_PORTLOCNNM + ')' == autoboxPort2.Text
                                  select port;

                    List<ServiceReference_HB.UM_Ports> tem1 = result1.ToList();
                    List<ServiceReference_HB.UM_Ports> tem2 = result2.ToList();
                    if (tem1 != null && tem1.Count > 0)
                        fid = tem1[0].POT_ID.ToString();
                    if (tem2 != null && tem2.Count > 0)
                        nid = tem2[0].POT_ID.ToString();
                }
                //服务航线
                // ServiceReference_HB.MainSeaRoutes serviceLine = comboxServiceLine.SelectedItem as ServiceReference_HB.MainSeaRoutes;

                if (txtSeaRoutes.Tag != null)
                {
                    sln_id = txtSeaRoutes.Tag.ToString();
                }
                //班期
                ServiceReference_HB.MainSeaRoutes flight = comboxVesselDate.SelectedItem as ServiceReference_HB.MainSeaRoutes;
                if (flight != null)
                {
                    flt_id = flight.ID.ToString();
                }
                if (IsAdd_Modefy)
                {
                    clientService.InsertToTable_ScheduleAsync(userid, txtVesselCNName.Text, txtVesselCNName.Tag == null ? "" : txtVesselCNName.Tag.ToString(), txtImportVoyage.Text, txtExportVoyage.Text,
                        eta, etd, state, terminal_id, ucloc, P_PILOTAGE, fid, nid, sln_id, flt_id, autoComENName_Add.Tag == null ? null : autoComENName_Add.Tag.ToString());
                    clientService.InsertToTable_ScheduleCompleted -= new EventHandler<ServiceReference_HB.InsertToTable_ScheduleCompletedEventArgs>(clientService_InsertToTable_ScheduleCompleted);
                    clientService.InsertToTable_ScheduleCompleted += new EventHandler<ServiceReference_HB.InsertToTable_ScheduleCompletedEventArgs>(clientService_InsertToTable_ScheduleCompleted);
                }
                else
                {// 更新
                    clientService.UpdateScheduleAsync(mSchedules.SCD_ID.ToString(), userid, txtVesselCNName.Text, txtVesselCNName.Tag == null ? "" : txtVesselCNName.Tag.ToString(), txtImportVoyage.Text, txtExportVoyage.Text,
                                       eta, etd, state, terminal_id, ucloc, P_PILOTAGE, fid, nid, flt_id, autoComENName_Add.Tag == null ? null : autoComENName_Add.Tag.ToString());
                    clientService.UpdateScheduleCompleted -= new EventHandler<ServiceReference_HB.UpdateScheduleCompletedEventArgs>(clientService_UpdateScheduleCompleted);
                    clientService.UpdateScheduleCompleted += new EventHandler<ServiceReference_HB.UpdateScheduleCompletedEventArgs>(clientService_UpdateScheduleCompleted);
                }
            }
            catch
            {
                progressbar.IsBusy = false;
            }
        }

        void clientService_UpdateScheduleCompleted(object sender, ServiceReference_HB.UpdateScheduleCompletedEventArgs e)
        {
            progressbar.IsBusy = false;
            string result = e.Result;
            if (result.Length < 1) return;
            if (result.Length > 1 && result.Substring(0, 1) != "1")
            {
                MessageBox.Show(e.Result);
                return;
            }

            string P_PILOTAGE = string.Empty;
            //引航标志
            if (rbtnYes.IsChecked.Value)
                P_PILOTAGE = "Y";
            else
                P_PILOTAGE = "N";
            mUM_VesselSchedules.VSL_ENNAME = txtVesselCNName.Tag == null ? "" : txtVesselCNName.Tag.ToString();
            mUM_VesselSchedules.VSL_CNNAME = txtVesselCNName.Text;
            mUM_VesselSchedules.SCD_IVOYAGE = txtImportVoyage.Text;
            mUM_VesselSchedules.SCD_EVOYAGE = txtExportVoyage.Text;
            // 预报位置
            ServiceReference_HB.UM_Ref_Code ref_code = comboxPort.SelectedItem as ServiceReference_HB.UM_Ref_Code;
            if (ref_code != null)
            {
                mUM_VesselSchedules.RV_MEANING = ref_code.RV_MEANING;
            }
            string mhuar1 = string.IsNullOrEmpty(this.txt_eta_h.Text) ? "00" : this.txt_eta_h.Text;
            string mhuar2 = string.IsNullOrEmpty(this.txt_etd_h.Text) ? "00" : this.txt_etd_h.Text;
            string mminete1 = string.IsNullOrEmpty(this.txt_eta_M.Text) ? "00" : this.txt_eta_M.Text;
            string mminete2 = string.IsNullOrEmpty(this.txt_etd_m.Text) ? "00" : this.txt_etd_m.Text;

            if (!string.IsNullOrEmpty(datePicker_eta.Text))
            {
                mUM_VesselSchedules.SCD_ETA = DateTime.Parse(datePicker_eta.Text + " " + mhuar1 + ":" + mminete1);
            }
            if (!string.IsNullOrEmpty(datePicker_etd.Text))
            {
                mUM_VesselSchedules.SCD_ETD = DateTime.Parse(datePicker_etd.Text + " " + mhuar2 + ":" + mminete2);
            }
            mUM_VesselSchedules.SCD_PILOTAGE = P_PILOTAGE;
            mUM_VesselSchedules.POT_FNAME = autoboxPort1.Text;
            mUM_VesselSchedules.POT_NNAME = autoboxPort2.Text;
            if (rbtnState1.IsChecked.Value)
            {
                mUM_VesselSchedules.SCD_STATUS = "预报";
            }
            else
            {
                mUM_VesselSchedules.SCD_STATUS = "确报";
            }
            //OnAddShipSchedule(sender, null);
            this.Close();

        }

        void clientService_InsertToTable_ScheduleCompleted(object sender, ServiceReference_HB.InsertToTable_ScheduleCompletedEventArgs e)
        {
            progressbar.IsBusy = false;
            string str = e.Result;
            if (str.Substring(0, 1) == "1")
            {
                MessageBox.Show(str.Substring(2, str.Length - 2));
                OnAddShipSchedule(sender, null);
            }
            else
            {
                MessageBox.Show(e.Result);
            }

            this.Close();
        }

        #endregion

        /// <summary>
        /// 根据英文船名得到该船所有的信息。
        /// </summary>
        /// <param name="enName"></param>
        /// <returns></returns>
        private ServiceReference_HB.ST_Vessels GetVesselBy_VSL_CNNAME(string enName)
        {
            var result = (from table in listVess
                          where table.VSL_CNNAME.Equals(enName)
                          select table).ToList();
            if (result != null && result.Count() > 0)
                return result[0] as ServiceReference_HB.ST_Vessels;
            else
                return null;
        }

        /// <summary>
        /// 查找服务航线。
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private ServiceReference_HB.MainSeaRoutes GetServiceLineByName(string name)
        {
            if (mListServiceLine != null)
            {

            }
            var result = from table in mListServiceLine
                         where table.ChildRouteName == name
                         select table;
            return result as ServiceReference_HB.MainSeaRoutes;

        }

        private void rbtnState2_Checked(object sender, RoutedEventArgs e)
        {
            if (rbtnState2 != null && rbtnState2.IsChecked.Value)
            {
                stackPanel_eta.Visibility = System.Windows.Visibility.Visible;
                stackPanel_etd.Visibility = System.Windows.Visibility.Visible;
            }
        }

        private void rbtnState1_Checked(object sender, RoutedEventArgs e)
        {
            if (rbtnState1 != null && rbtnState1.IsChecked.Value)
            {
                stackPanel_eta.Visibility = System.Windows.Visibility.Collapsed;
                stackPanel_etd.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        private void txtImportVoyage_LostFocus(object sender, RoutedEventArgs e)
        {
            txtImportVoyage.Text = txtImportVoyage.Text.ToUpper();
        }

        private void txtExportVoyage_LostFocus(object sender, RoutedEventArgs e)
        {
            txtExportVoyage.Text = txtExportVoyage.Text.ToUpper();
        }

        private void ChildWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            ClearText();
        }

        private void comboxVesselDate_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count == 0) return;
            ServiceReference_HB.MainSeaRoutes sera = e.AddedItems[0] as ServiceReference_HB.MainSeaRoutes;
            if (txtSeaRoutes.Tag != null && sera != null)
            {
                //显示预分码头.
                clientService.GetTermail_ScheduleAsync(int.Parse(txtSeaRoutes.Tag.ToString()), sera.ID);
                clientService.GetTermail_ScheduleCompleted -= new EventHandler<ServiceReference_HB.GetTermail_ScheduleCompletedEventArgs>(clientService_GetTermail_ScheduleCompleted);
                clientService.GetTermail_ScheduleCompleted += new EventHandler<ServiceReference_HB.GetTermail_ScheduleCompletedEventArgs>(clientService_GetTermail_ScheduleCompleted);
            }
        }

        void clientService_GetTermail_ScheduleCompleted(object sender, ServiceReference_HB.GetTermail_ScheduleCompletedEventArgs e)
        {
            //显示预分码头, 完成事件。
            ObservableCollection<ServiceReference_HB.MainSeaRoutes> col = e.Result;
            if (col != null && col.Count >= 1)
            {
                this.txtTerminal.Text = col[0].RouteName;
                this.txtTerminal.Tag = col[0].ID;
            }
            else
            {
                this.txtTerminal.Text = "";
                this.txtTerminal.Tag = null;
            }
        }

        private void dataGridVesselName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (dataGridVesselName.SelectedItem == null) return;
            ServiceReference_HB.ST_Vessels tem = dataGridVesselName.SelectedItem as ServiceReference_HB.ST_Vessels;
            if (tem != null)
            {
                autoComENName_Add.Text = tem.VSL_ENNAME + "(" + tem.VSL_UNCODE + ")";
                txtVesselCNName.Text = tem.VSL_CNNAME;
                txtVesselCNName.Tag = tem.VSL_ENNAME;
                autoComENName_Add.Tag = tem.VSL_ID.ToString();
            }
            else
            {
                txtVesselCNName.Text = "";
                txtVesselCNName.Tag = null;
                autoComENName_Add.Tag = null;
            }
        }

        private void dataGridPort1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
             ServiceReference_HB.UM_Ports port1= dataGridPort1.SelectedItem as ServiceReference_HB.UM_Ports;
             autoboxPort1.Text = port1.POT_PORTCD + "(" + port1.POT_PORTLOCNNM + ")";
        }

        private void dataGridPort2_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ServiceReference_HB.UM_Ports port2 = dataGridPort2.SelectedItem as ServiceReference_HB.UM_Ports;
            autoboxPort2.Text = port2.POT_PORTCD + "(" + port2.POT_PORTLOCNNM + ")";
        }


    }//end class
}

